var mcShopApp = angular.module('mcShopApp', ['ngTable','ngRoute','ngDialog']);
//Configure our routes
mcShopApp.config(function($routeProvider) {
	$routeProvider
	.when('/', {
		templateUrl : 'login.html',
		controller  : 'shopLoginController'
	})
	.when('/account', {
		templateUrl : 'account.html',
		controller  : 'shopAccountController'
	})
	.when('/change-password', {
		templateUrl : 'change-password.html',
		controller  : 'changePasswordController'
	})
	.when('/forgoten', {
		templateUrl : 'forgoten.html',
		controller  : 'forgotenController'
	})
	.when('/reset-password', {
		templateUrl : 'reset-password.html',
		controller  : 'shopResetPasswordController'
	})
	.when('/expire-password', {
		templateUrl : 'expire-password.html',
		controller  : 'shopExpirePasswordController'
	})
	.when('/notifications', {
		templateUrl : 'notifications.html',
		controller  : 'shopNotificationsController'
	})
	.when('/shop-notifications-history', {
		templateUrl : 'shop-notifications-history.html',
		controller  : 'shopNotificationsHistoryController'
	})
	.when('/order-history', {
		templateUrl : 'order-history.html',
		controller  : 'shopOrderHistoryController'
	})
	.when('/discounts', {
		templateUrl : 'discounts.html',
		controller  : 'discountsController'
	})
	.when('/complaints', {
		templateUrl : 'complaints.html',
		controller  : 'shopComplaintsController'
	})
	.when('/reviews', {
		templateUrl : 'reviews.html',
		controller  : 'shopReviewsController'
	})
	.when('/shop-orders-report', {
		templateUrl : 'shop-orders-report.html',
		controller  : 'shopOrdersReportController'
	})
	.when('/reports', {
		templateUrl : 'reports.html',
		controller  : 'reportsController'
	})
	.when('/logout', {
		templateUrl : 'login.html',
		controller  : 'shopLogoutController'
	})
});
//activate the menu 

/*angular.element(document).ready(function ()
{
alert('active');
		$('#menuactive ul li a').each(function(path){
		//alert('hi');
			var presentPage=this.href.split('#');
			alert(path);
		
		});
});*/
//End activate the Menu
//reports for shop orders report
google.load('visualization', '1', {packages: ['corechart']});
mcShopApp.controller('shopOrdersReportController', function($scope,$sce,$http) {
  $scope.getReportsPieChart = function() {
		var shop_id = JSON.parse(sessionStorage["shop_user_id"]);
			var dataObj = {
				shop_id			:	shop_id
			};
			$http.post(webServiceUrl+'shop-orders',dataObj)
				.success(function(response) {
					$scope.responseData=[
						  ['TotalOrders',response.totOrders],
						  ['TotRenewalOrders',response.totrenewalOrders],
						  ['SentpriceToAdmin',response.totSentorders],
						  ['ConfirmedOrders',response.totConfirmedOrders],
						  ['DeliveredOrders',response.totDeliveredOrders],
						  ['DiscountsUnpaidToAdmin',response.totunPaidOrders],
						  ['DiscountsPaidToAdmin',response.totPaidOrders]
					];
					// console.log($scope.response12);return false;
	});
	}
});
mcShopApp.controller('reportsController', function($scope,$sce,$http) {
  $scope.getReportsPieChart = function() {
		var shop_id = JSON.parse(sessionStorage["shop_user_id"]);
			$http.get(webServiceUrl+'shop-com-rp-rv-rtng/shop-'+shop_id)
				.success(function(response) {
				$scope.ratingsHide=true;
				if(response.cntRating1!=0){
					$scope.stars1=response.cntRating1;
				}else{
					$scope.stars1=response.cntRating1;
				}if(response.cntRating2!=0 ){
					$scope.stars2=response.cntRating2;
				}else{
					$scope.stars2=response.cntRating2;
				}if(response.cntRating3!=0 ) {
					$scope.stars3=response.cntRating3;
				}else{
					$scope.stars3=response.cntRating3;
				}if(response.cntRating4!=0) {
					$scope.stars4=response.cntRating4;
				}else{
					$scope.stars4=response.cntRating4;
				}if(response.cntRating5!=0){
					$scope.stars5=response.cntRating5;
				}else{
					$scope.stars5=response.cntRating5;
				}
				if(response.cntRating5==0 && response.cntRating4==0 && response.cntRating3==0 && response.cntRating2==0 && response.cntRating1==0 ){
					$scope.ratingsHide=false;
				}
					if( response.cntComplanits!=0 || response.cntReplies!=0 || response.cntReviews!=0 ){
						$scope.responseData=[
											  ['Complaints',response.cntComplanits],
											  ['Repliesofcomplaints',response.cntReplies],
											  ['Reviews',response.cntReviews]
											];
					}
				});
				
	}
});

  mcShopApp.directive('activeLink', ['$location', function(location) {
    return {
      restrict: 'A',
      link: function($scope, $element, $attrs, $controller) {
        var clazz = $attrs.activeLink;
        var path = $attrs.href;
        path = path.substring(1); //hack because path does not return including hashbang
		
        $scope.location = location;
        $scope.$watch('location.path()', function(newPath) {
          if (path === newPath) {
            $element.addClass(clazz);
          } else {
            $element.removeClass(clazz);
          }
        });
      }
    };
  }]); 
mcShopApp.directive('chart', function() {
        return {
          restrict: 'E,A',
          link: function($scope, $elm, $attr) {
            // Create the data table.
			$scope.getReportsPieChart();
			$scope.$watch('responseData', function (newMyData) {

			
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Topping');
            data.addColumn('number', 'Slices');
			if(typeof newMyData!="undefined"){
				data.addRows(newMyData);
			}
            // Set chart options
            var options = {'title':'Shop Orders Reports',
                           'width':600,
                           'height':600};

            // Instantiate and draw our chart, passing in some options.
            var chart = new google.visualization.PieChart($elm[0]);
            chart.draw(data, options);
			});
          }
      }
    });
//Login Page Controller
mcShopApp.controller('shopLoginController', function($scope,$sce,$http,$location) {
	var self = this;
	$scope.errorLoginMessage='';
	$scope.setActivePage = function() {
      if(typeof sessionStorage["shop_user_id"]!='undefined'){
		$scope.user_id 		= 	JSON.parse(sessionStorage["shop_user_id"]);
		$scope.email 		= 	JSON.parse(sessionStorage["shop_email"]);
		$scope.phone 		= 	JSON.parse(sessionStorage["shop_phone"]);
		$scope.location 	=	JSON.parse(sessionStorage["shop_location"]);
		$scope.headding		=	$sce.trustAsHtml('<div class="text_l top_strip_left_text"><span id="updateLocation" name="updateLocation" >'+$scope.location+'</span><span id="updatePhone" name="updatePhone" >Ph:&nbsp;'+$scope.phone+'</span><span>Email:&nbsp;'+$scope.email+'</div><div class="text_r top_strip_right_text"><span>Welcome to medicart</span><span id="myaccounthid"><a href="#account">My Account</a></span><span id="loginLogout"><a href="#logout">Logout</a></span></div>');
		window.location="#/account";
		}else{
			$scope.headding		=	$sce.trustAsHtml('<div id="headding" class="row_text_lr"><div class="text_r top_strip_right_text"><span>Welcome to medicart</span><span id="loginLogout"><a href="#">Login</a></span><span id="registerhid"><a href="#/shop-register">Register</a></span></div></div>');
			$scope.loading		=	$sce.trustAsHtml('');
			$scope.errorLoginMessage='';
		}
}
	
	$scope.getNotifications = function(userId) {
		$http.get(webServiceUrl+'notifications/'+'3'+'-'+userId)
		.success(function(response) {
			if(response.count!=0){
				$scope.notificationsCount=response.count;
			}else{
				$scope.notificationsCount=0;
			}
		});
	}
	$scope.loginFormShop = function(shopLoginForm) {
		$scope.loading		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
		var dataObj = {
			email			:	shopLoginForm.username.$viewValue,
			pwd				:	shopLoginForm.password.$viewValue,
			user_type_id	:	'3'
		};
		$http.post(webServiceUrl+'login',dataObj)
		.success(function(response) {
			$scope.loading		=	$sce.trustAsHtml('');
			$scope.errorLoginMessage="";
			if(response.value!=0){
				$scope.UserDetails=response.UserDetails;
				sessionStorage.setItem( 'shop_user_id', JSON.stringify($scope.UserDetails.user_id) );		
				sessionStorage.setItem( 'shop_email', JSON.stringify($scope.UserDetails.email) );
				sessionStorage.setItem( 'shop_user_name', JSON.stringify($scope.UserDetails.user_name) );
				sessionStorage.setItem( 'shop_phone', JSON.stringify($scope.UserDetails.phone) );
				sessionStorage.setItem( 'shop_location', JSON.stringify($scope.UserDetails.location) );
				window.location="#/account";
			}else{
				$scope.errorLoginMessage="Entered email or password is wrong";
			}
		});
	}
	$scope.changeNotificationStatus = function(orderId,type,orderType,usertype,updatetype) {
		$scope.loading		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
		var dataObj = {
			OrderType			:	orderType,
			userType			:	usertype,
			updatetype			:	updatetype
		};	
		$http.put(webServiceUrl+'notifications/'+orderId,dataObj)
		.success(function(data) {
			if(data.value==1){
				if(type==1){
					window.location="#/complaints";
				}else if(type==2){
					window.location="#/reviews";
				}else if(type==3){
					window.location="#/order-history";
				}else if(type==4){
					window.location="#/order-history";
				}else if(type==5){
					window.location="#/discounts";
				}
			}
		});
	}
	$scope.getOptionsFromForm = function(type){
			if(type=='Order'){
				var opt = {callback:pageselectCallbackOrder};
			}else if(type=='Renewal'){
				var opt = {callback:pageselectCallbackRenewal};
			}else if(type=='Review'){
				var opt = {callback:pageselectCallbackReview};
			}else if(type=='Discount'){
				var opt = {callback:pageselectCallbackDiscount};
			}else if(type=='Complints'){
				var opt = {callback:pageselectCallbackComplints};
			}else if(type=='Services'){
				var opt = {callback:pageselectCallbackServices};
			}else if(type=='ShopOrder'){
				var opt = {callback:pageselectCallbackShopOrder};
			}else if(type=='ShopDiscount'){
				var opt = {callback:pageselectCallbackShopDiscount};
			}else if(type=='ShopComplaints'){
				var opt = {callback:pageselectCallbackShopComplaints};
			}else if(type=='ShopReview'){
				var opt = {callback:pageselectCallbackShopReview};
			}
			$("input:text").each(function(){
				opt[this.name] = this.className.match(/numeric/) ? parseInt(this.value) : this.value;
			});
			var htmlspecialchars ={ "&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;"}
			$.each(htmlspecialchars, function(k,v){
				opt.prev_text = opt.prev_text.replace(k,v);
				opt.next_text = opt.next_text.replace(k,v);
			})
			return opt;
	 }
	 $scope.pageselectCallbackComplints = function(page_index, jq) {
		alert(page_index);
	 }
	$scope.setActivePage();
});
// Account Page Controller
mcShopApp.controller('shopAccountController', function($scope,$http,$sce,$location) {
	$scope.p = {};
	$scope.phoneNumbr = /^\+?\d{2}[- ]?\d{3}[- ]?\d{5}$/;
	$scope.accountForm = function(accForm) {
		$scope.accloading		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
		var user_id = JSON.parse(sessionStorage["shop_user_id"]);
		var accObj=this.p;
		$http.put(webServiceUrl+'shopregister/'+user_id,accObj)
		.success(function(response) {
			$scope.regloading		=	$sce.trustAsHtml('');
			$scope.passwordError	=	'';
			if(response.value=='1'){
				$scope.accloading		='';
				sessionStorage.setItem( 'shop_user_name', JSON.stringify(accObj.user_name) );
				sessionStorage.setItem( 'shop_phone', JSON.stringify(accObj.phone) );
				sessionStorage.setItem( 'shop_location', JSON.stringify(accObj.location) );
				$('#success_alert').show();
				$scope.successDiv		= Account_page_success_message;
				$("html, body").animate({ scrollTop: 0 }, 600);
				$('#success_alert').delay(3000).fadeOut('slow');
				$scope.setActivePage();
			}
		});
	}
	$scope.successDiv		='';
	$scope.accloading		='';
	$scope.setActivePage();
	if(typeof sessionStorage["shop_user_id"]!='undefined'){
		var user_id = JSON.parse(sessionStorage["shop_user_id"]);
		$scope.posts={};
		 $http.get(webServiceUrl+'registration/'+user_id)
		.success(function(response) {
			$scope.posts = [response.data];
			$scope.getNotifications(user_id);
		});
	}else{
		location.href="#";
	}
});
mcShopApp.controller('changePasswordController', function($scope,$sce,$http,$location) {
	$scope.cpwdloading		=	$sce.trustAsHtml('');
	$scope.passwordcError='';
	$scope.cp = {};
	$scope.changePwdForm = function(cwdForm) {
		$scope.cpwdloading		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
		var user_id = JSON.parse(sessionStorage["shop_user_id"]);
		var cpwdObj=this.cp;
		if(cpwdObj.newPassword != cpwdObj.cnf_password){
			$scope.cpwdloading		=	$sce.trustAsHtml('');
			$scope.passwordcError	=	Change_errorconfirm_password;
		}else{
			$http.put(webServiceUrl+'changepassword/'+user_id,cpwdObj)
			.success(function(response) {
				$scope.cpwdloading		=	$sce.trustAsHtml('');
				$scope.passwordcError	=	'';
				if(response.value=='1'){
					$('#success_alert').show();
					$scope.successcDiv		= Change_successpassword_message;
					$("html, body").animate({ scrollTop: 0 }, 600);
					$('#success_alert').delay(3000).fadeOut('slow');
					$scope.cp.old_password="";
					$scope.cp.newPassword="";
					$scope.cp.cnf_password="";
				}else{
					$('#error_alert').show();
					$scope.errorDiv		= Changepassword_error_message;
					$("html, body").animate({ scrollTop: 0 }, 600);
					$('#error_alert').delay(3000).fadeOut('slow');
				}
			});
		}
	}
	if(typeof sessionStorage["shop_user_id"]!='undefined'){
		var user_id = JSON.parse(sessionStorage["shop_user_id"]);
		$scope.getNotifications(user_id);
			/*var current = $location.path().substring(1);
			if(current==='password'){
			var myEl = angular.element(document.querySelector('#password'));
			myEl.addClass('arrow_left'); 
			alert(myEl);
				//$('#account').addClass('arrow_left');
			}*/
		//$('#password').addClass('arrow_left');
	}else{
		location.href="#";
	}
});
mcShopApp.controller('forgotenController', function($scope,$sce,$http) {
	if(typeof sessionStorage["shop_user_id"]=='undefined'){
	    $scope.forgetReload		=	$sce.trustAsHtml('');
		$scope.successfpassword='';
		$scope.forgetFormShop = function(ngForm) {
			$scope.forgetReload		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
			var dataObj = {
				email	:	ngForm.inputuser.$viewValue,
				type	:	'3'
			};
				$http.post(webServiceUrl+'forgetpassword',dataObj)
				.success(function(response) {
					$scope.forgetReload		=	$sce.trustAsHtml('');
					$scope.successfpassword	=	'';
					if(response.value=='1'){
						$('#success_alert').show();
						$scope.successcDiv		= Forgotpassword_success_message;
						$("html, body").animate({ scrollTop: 0 }, 600);
						$('#success_alert').delay(3000).fadeOut('slow');
					}else{
						$('#error_alert').show();
						$scope.errorDiv		= Forgotpassword_error_message;
						$("html, body").animate({ scrollTop: 0 }, 600);
						$('#error_alert').delay(3000).fadeOut('slow');
					}
				});
		}
	}else{
		window.location="#/account";
	}
});
mcShopApp.controller('shopResetPasswordController', function($scope,$sce,$http) {
   var path = window.location.href;
   path = path.replace(/\/$/, "");
   path = decodeURIComponent(path);
   var id=path.split('=');
   var token=id[1];
   $http.get(webServiceUrl+'forgetpassword/'+token)
	  .success(function(response) {
			
			if(response.value=="0"){
				window.location="#/expire-password";
			}else {
			    $scope.setActivePage();
				$scope.resetPwdReload		=	$sce.trustAsHtml('');
				$scope.passwordcError='';
				$scope.r = {};
				$scope.resetPasswordForm = function(resetForm) {
					$scope.resetPwdReload		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
					var cpwdObj=this.r;
					var path = window.location.href;
					path = path.replace(/\/$/, "");
					path = decodeURIComponent(path);
					var id=path.split('=');
					var token=id[1];
					if(cpwdObj.resetPwd != cpwdObj.confirmPassword){
						$scope.resetPwdReload		=	$sce.trustAsHtml('');
						$scope.passwordcError	=	Change_errorconfirm_password;
					}else{
						var dataObj = {
							cnf_password	:	resetForm.confirmPassword.$viewValue
						};
						$http.put(webServiceUrl+'forgetpassword/'+token,dataObj)
						.success(function(response) {
							$scope.resetPwdReload		=	$sce.trustAsHtml('');
							$scope.passwordcError	=	'';
							if(response.value=='1'){
								$('#success_alert').show();
								$scope.successcDiv		= Resetpassword_success_message;
								$("html, body").animate({ scrollTop: 0 }, 600);
								$('#success_alert').delay(3000).fadeOut('slow');
								
							}else{
								$('#error_alert').show();
								$scope.errorDiv		= Resetpassword_error_message;
								$("html, body").animate({ scrollTop: 0 }, 600);
								$('#error_alert').delay(3000).fadeOut('slow');
							}
						});
					}
				}
			}

		});
});
mcShopApp.controller('shopLogoutController', function($scope,$sce) {
	sessionStorage.removeItem("shop_user_id");
	sessionStorage.removeItem("shop_email");
	sessionStorage.removeItem("shop_user_name");
	sessionStorage.removeItem("shop_phone");
	sessionStorage.removeItem("shop_location");
	$scope.setActivePage();
});
mcShopApp.controller('shopExpirePasswordController', function($scope,$sce,$http) {

});
mcShopApp.controller('shopNotificationsController', function($scope,$sce,$http) {
		$scope.viewComplaintNotifications = function (orderId,orderType,usertype ){
			$scope.changeNotificationStatus(orderId,1,orderType,usertype,3 );
		}
		$scope.viewReviwNotifications = function (orderId,orderType,usertype ){
			$scope.changeNotificationStatus(orderId,2,orderType,usertype,3 );
		}
		$scope.viewSendQuotationNotifications = function (orderId,orderType,usertype){
			$scope.changeNotificationStatus(orderId,3,orderType,usertype,2 );
		}
		$scope.viewConfirmedNotifications = function (orderId,orderType,usertype){
			$scope.changeNotificationStatus(orderId,4,orderType,usertype,2 );
		}
		$scope.viewDiscountNotifications = function (orderId,orderType,usertype){
			$scope.changeNotificationStatus(orderId,5,orderType,usertype,3 );
		}
	if(typeof sessionStorage["shop_user_id"]!='undefined'){
		$scope.notis={};
		var user_id = JSON.parse(sessionStorage["shop_user_id"]);
		$('#notifications').addClass('arrow_left');
		$http.get(webServiceUrl+'notifications/3-'+user_id)
		.success(function(response) {
			if(response.count!='0'){
				$scope.getNotifications(user_id);
				$scope.notis=response.notifications;
				//console.log($scope.notis);
			}else{
				$scope.emptyNotifications="Notifications Empty";
			}
		});
	}else{
		location.href="#";
	}
});
mcShopApp.controller('shopComplaintsController', function($scope,$sce,$http,$compile) {
	$scope.replyValue = true;
	$scope.replyBox = true;
	$scope.replay = function (complaint_on_id,complaint_id,shop_id,user_name){
	//alert(complaint_id);
		$('#replayP'+complaint_id).hide();
		var acHtml2="<div  class='media replay_comment_show' id='replay_comment"+complaint_id+"' ng-show='"+complaint_id+"'><a class='pull-left' href='#'><img src='https://lh3.googleusercontent.com/uFp_tsTJboUY7kue5XAsGA=w48-c-h48' class='media-object img_profile'></a><div class='media-body'><textarea id='replaytext"+complaint_id+"' class='span10' placeholder='Add a Replay' ng-model='rep.address"+complaint_id+"'></textarea><p>Replay by "+user_name+" <a href='javascript:void(0);' class='submit_comment' ng-click='submitReplay("+shop_id+","+complaint_id+","+complaint_on_id+",rep.address"+complaint_id+")'>Submit Comment</a></p><span id='loading"+complaint_id+"'></span></div><span style='color:red' id='errortext"+complaint_id+"'></span></div>";
		var emt1 = $compile(acHtml2)($scope);
		$('#replytextBOxApend'+complaint_id).append(emt1);
	}
	$scope.submitReplay = function (shop_id,complaint_id,complaint_on_id,reply_text){
		var loading='<img src="images/ajax-loader.gif"/>';
		var load= $compile(loading)($scope);
			$('#loading'+complaint_id).append(load);
			$('#errortext'+complaint_id).empty();
		$scope.notius	    = "";
		var complaint_relpier_id = JSON.parse(sessionStorage["shop_user_id"]);
		if(typeof reply_text=="undefined"){
			$('#loading'+complaint_id).empty();
			var errortext='<p>Enter The reply in the text box</p>';
			var error= $compile(errortext)($scope);
			$('#errortext'+complaint_id).append(error);
		}else{
			var dataObj = {
				complaint_id         :  complaint_id,
				complaint_relpier_id :  complaint_relpier_id,
				reply_text           :  reply_text,
				tracking_id          :  complaint_on_id,
				user_id              :  '0',
				compliantType        :  "Complaint",
				shopId               :  shop_id
			};
			$http.post(webServiceUrl+'renuwalorder',dataObj)
			.success(function(response) {
				$('#errortext'+complaint_id).empty();
				if(response.status=='success'){
					$('#loading'+complaint_id).empty();
					$('#replay_comment'+complaint_id).hide();
					$('#replayP'+complaint_id).hide();
					var acHtml="<div class='media'><a class='pull-left' href='#'><img src='https://lh3.googleusercontent.com/uFp_tsTJboUY7kue5XAsGA=w48-c-h48' class='media-object img_profile'></a><div class='media-body'><h4 class='media-heading'>Replay TRACKING ID:"+complaint_on_id+"</h4><p>"+reply_text+"</p></div></div>";
					var emt = $compile(acHtml)($scope);
					$('#replytextappend'+complaint_id).append(emt);
				}
			});
		}
	}
	if(typeof sessionStorage["shop_user_id"]!='undefined'){
		$scope.notis={};
		var user_id = JSON.parse(sessionStorage["shop_user_id"]);
		$('#complaints').addClass('arrow_left');
		$http.get(webServiceUrl+'shop-complaints/'+user_id)
		.success(function(response) {
			if(response.count!='0'){
				$scope.getNotifications(user_id);
				$scope.notis=response.result;
				console.log($scope.notis);
			}else{
				$scope.emptyNotifications="No Data";
			}
		});
	}else{
		location.href="#";
	}
});
mcShopApp.controller('shopNotificationsHistoryController', function($scope,$sce,$http) {
	if(typeof sessionStorage["shop_user_id"]!='undefined'){
		$scope.notish={};
		var user_id = JSON.parse(sessionStorage["shop_user_id"]);
		var dataObj = {
			usertype			:	'3',
			user_id				:	user_id,
		};
		$http.post(webServiceUrl+'notifications',dataObj)
		.success(function(response) {
			if(response.value!='0'){
				$scope.getNotifications(user_id);
				$scope.notish=response.noitifications;
			}else{
				$scope.emptyNotifications="Notifications history table Empty";
			}
		});
	}else{
		location.href="#";
	}
});
mcShopApp.controller('shopOrderHistoryController', function($scope,$sce,$http,ngTableParams,ngDialog,$compile) {
	var shop_id = JSON.parse(sessionStorage["shop_user_id"]);
	$scope.allPriscription		=	$sce.trustAsHtml('');
	$scope.allDetails			=	$sce.trustAsHtml('');
	$scope.send_quotation_price		=	$sce.trustAsHtml('');
	$scope.index = 0;
	$scope.openPopups = function(type,user_m_id) {
		if(type==1){
			var openPopupId="viewPriscription.html";
		}else if(type==2){
			var openPopupId="viewDetails.html";
		}else if(type==3){
			var openPopupId="viewAllPreImages.html";
		}else if(type==4){
			var openPopupId="sendPrice.html";
		}
		$scope.loadPre		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
		ngDialog.open({
			template: openPopupId,
			className: 'ngdialog-theme-plain',
			scope:$scope
		});
	$http.get(webServiceUrl+'getprescription/'+user_m_id+'-'+'0'+'-'+shop_id)
		.success(function(response) {
			$scope.ErrorPrice="";
			var viewDetailes="";
			var viewallImages=[];
			var htmlPopup="";
			var Popup="";
			var pdata=response.result;
			var viewAll='<tr><th>Tablet name</th><th>Quantity</th></tr>';
			$.each(pdata, function (index,Object) {
				//All Tabletes Pop up
				var prdetails=Object.prescription_details;
				var detailss=prdetails.split('**');
				if(detailss.length>0){
					for(var i=0;i<=(detailss.length-1);i++){
						var namess=detailss[i].split('$$');
						viewAll+='<tr><th>'+namess[0]+'</th>'+'<th>'+namess[1]+'</th></tr>';
					}
				}
				//End
				//All Order Details Pop Up
				if(Object.auto_renewal==0 || Object.auto_renewal==null){
					var auto_renewal='No';
				}else{
					var auto_renewal='Yes';
				}
				if(Object.each_days==0 || Object.auto_renewal==null){
					var each_days='No';
				}else{
					var each_days=Object.each_days;
				}
				if(Object.delivered_date=="" || Object.delivered_date==null){
					var deliverdDate="Not delivered";
				}else{
					var deliverdDate=Object.delivered_date;
				}
				if(Object.immediate==0 || Object.immediate==null){
					var immidiate='Not Immidiate';
				}else{
					var immidiate='Yes';
				}
				if(Object.availabletime==0 || Object.availabletime==null){
					var availabletime='Not Mention';
				}else{
					var availabletime=Object.availabletime;
				}
				viewDetailes+='<tr><th>Tracking Id</th><th>'+Object.user_medicine_order_id+'</th></tr>'+'<tr><th>Price</th><th>'+Object.price+'</th></tr>'+
					'<tr><th>Discount</th><th>'+Object.discount+'</th></tr>'+
					'<tr><th>Auto renewal </th><th>'+auto_renewal+'</th></tr>'+
					'<tr><th>Days</th><th>'+each_days+'</th></tr>'+
					'<tr><th>Delivered date</th><th>'+deliverdDate+'</th></tr>'+
					'<tr><th>Landmark </th><th>'+Object.landmark+'</th></tr>'+
					'<tr><th>Phone number </th><th>'+Object.phone+'</th></tr>'+
					'<tr><th>Alternative phone number</th><th>'+Object.alterphone+'</th></tr>'+
					'<tr><th>Address</th><th>'+Object.address+'</th></tr>'+
					'<tr><th>Immidiate</th><th>'+immidiate+'</th></tr>'+
					'<tr><th>Available time</th><th>'+availabletime+'</th></tr>';
				//End
				//All Prescription Images Pop Up
					var imagesss=Object.prescription_upload_path;
					var imagespre=imagesss.split('**');
					if(imagespre.length>0){
						for(var img=0;img<=(imagespre.length)-1;img++){
							viewallImages[img]=uploadImgUrl+imagespre[img];
						}
					}
				//End
					//htmlPopup+='<div id="price'+Object.order_delivery_details_id+'" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-header"><h3 id="myModalLabel">Send Price</h3></div><div id="popup" class="modal-body">';
					htmlPopup+='<form id="discounttForm"><p>Tracking Id:'+Object.user_medicine_order_id+'</p>';
					htmlPopup+='<p>Price:<input type="text" id="pricevalue" name="pricevalue"/></p>'+
					'<p><input type="button" id="buttonPrice" name="buttonPrice" value="Send" ng-click="sendPriceToOrder('+Object.order_delivery_details_id+','+Object.user_medicine_order_id+')"/><span>{{ErrorPrice}}</span></p>';
					htmlPopup+='</form>'+
						'<span id="sendsuccess" style="color:green"></span>';
					//htmlPopup+='</div></div>';
					//$('#price'+Object.order_delivery_details_id).modal('show');
					
			});
			$scope.loadPre =$sce.trustAsHtml("");
			$scope.allPriscription		=	$sce.trustAsHtml(viewAll);
			$scope.allDetails		=	$sce.trustAsHtml(viewDetailes);
			$scope.images = viewallImages;
			Popup = $compile(htmlPopup)($scope);
			$('#sendprice').append(Popup);
			
		});
	}
	$scope.updateTsPrevious = function() {
		$scope.tsPrevious = +new Date();
	}
	$scope.updateTsNext = function() {
		$scope.tsNext = +new Date();
	}
	$scope.orderConfirm = function(tracking_id) {
		$scope.status="";
		var user_id = JSON.parse(sessionStorage["shop_user_id"]);
		var dataObj = {
			tracking_id:tracking_id,
			compliantType:"OrderConfirmed",
			complaint_id:"0"
		};	
		$http.put(webServiceUrl+'shop-discount-refunds/'+tracking_id+'-'+user_id,dataObj)
		.success(function(response) {
			if(response.value==1){
				var acHtml="<a href='javascript:void(0)' ng-click='openPopups(2,"+tracking_id+")'>View</a>";
				var emt = $compile(acHtml)($scope);
				$('#b'+tracking_id).html('');
				$('#status'+tracking_id).html('');
				$("#status"+tracking_id).append('Processed');
				$('#b'+tracking_id).append(emt);
				
			}
		});
	}
	$scope.sendPriceToOrder = function(order_delivery_details_id,tracking_id) {
		var shop_id = JSON.parse(sessionStorage["shop_user_id"]);
		var price=$('#pricevalue').val();
		if(price==""){
			$scope.ErrorPrice='Please enter price';
		}
		else{
			$scope.ErrorPrice="";
			var dataObj = {
				price:price,
				t_id:tracking_id,
				complaintType:"sendPrice",
				shop_id:shop_id,
				user_id:"0",
				admin_id:"0",
			};
			$http.put(webServiceUrl+'shop-orders/'+order_delivery_details_id,dataObj)
			.success(function(response) {
					ngDialog.close({
						template: sendprice.html,
						className: 'ngdialog-theme-plain',
						scope:$scope
					});
					if(response.value==1){
							$scope.getNotifications(shop_id);
							var acHtml2="<a href='javascript:void(0)' ng-click='openPopups(2,"+tracking_id+")'>View</a>";
								var emt1 = $compile(acHtml2)($scope);
								$('#b'+tracking_id).html('');
								$('#status'+tracking_id).html('');
								$("#status"+tracking_id).append('Sent Price');
								$('#b'+tracking_id).append(emt1);
					}
			});
		}
	}
	if(typeof sessionStorage["shop_user_id"]!='undefined'){
		var user_id = JSON.parse(sessionStorage["shop_user_id"]);
		$http.get(webServiceUrl+'shop-orders/'+user_id)
		.success(function(response) {
			if(response.value==1){
				$scope.getNotifications(user_id);
				var data=response.result;
				$.each(data, function (index,Object) {
					if(Object.prescription_upload_path!=""){
						var imagess=Object.prescription_upload_path;
						var images=imagess.split('**');
						data[index].preImageLength=images.length;
						if(images.length>0){
						  for(var i=0;i<1;i++){
							   if(images[i]!=null){
									data[index].preImage=uploadImgUrl+images[i];
								}else{
									data[index].preImage=uploadImgUrl+'default.jpg';
								}
							}
						}
					}else{
						data[index].preImage=uploadImgUrl+'default.jpg';
					}
					var pdetails=Object.prescription_details;
					var details=pdetails.split('**');
					if(details.length>0){
						for(var i=0;i<1;i++){
							if(typeof details[i]!='undefined'){
								var names=details[i].split('$$');
								data[index].Tabletname=names[0];
								data[index].Quantity=names[1];
								data[index].preLength=details.length;
							}
						}
					}
				});	
				$scope.tableParams = new ngTableParams({
					page: 1, 
					count: 10
				}, {
					total: data.length,
					getData: function($defer, params) {
						$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
					}
				});
			}else{
				$scope.getNotifications(user_id);
				$scope.emptyOrders=errornodata_message;
			}
		});
	}else{
		location.href="#";
	}
});
mcShopApp.directive('wallopSlider', function () {
    return {
      template: '<div class="wallop-slider {{animationClass}}"><ul class="wallop-slider__list"><li class="wallop-slider__item {{itemClasses[$index]}}" ng-repeat="i in images"><img src="{{i}}"></li></ul><button ng-show="images.length>1" class="st-button wallop-slider__btn wallop-slider__btn--previous btn btn--previous" ng-disabled="prevDisabled" ng-click="onPrevButtonClicked()">Previous</button><button ng-show="images.length>1" class="st-button wallop-slider__btn wallop-slider__btn--next btn btn--next" ng-disabled="nextDisabled" ng-click="onNextButtonClicked()">Next</button></div>',
      restrict: 'EA',
      transclude: true,
      replace: false,
      scope: {
        images: '=',
        animation: '@',
        currentItemIndex: '=',
        onNext: '&',
        onPrevious: '&'
      },
      controller: function($scope, $timeout) {

        $scope.itemClasses = [];

        $scope.$watch('images', function(images) {
          if (images.length) {
            _goTo(0);
          }
        });

        $scope.$watch('itemClasses', function(itemClasses) {
          console.log('itemClasses', itemClasses);
        });

        // set animation class corresponding to animation defined in CSS. e.g. rotate, slide
        if ($scope.animation) {
          $scope.animationClass = 'wallop-slider--' + $scope.animation;
        }

        var _displayOptions = {
          btnPreviousClass: 'wallop-slider__btn--previous',
          btnNextClass: 'wallop-slider__btn--next',
          itemClass: 'wallop-slider__item',
          currentItemClass: 'wallop-slider__item--current',
          showPreviousClass: 'wallop-slider__item--show-previous',
          showNextClass: 'wallop-slider__item--show-next',
          hidePreviousClass: 'wallop-slider__item--hide-previous',
          hideNextClass: 'wallop-slider__item--hide-next'
        };

        function updateClasses() {
          if ($scope.itemClasses.length !== $scope.images.length) {
            $scope.itemClasses = [];
            for (var i=0; i<$scope.images.length; i++) {
              $scope.itemClasses.push('');
            }
          }
        }
        function _nextDisabled() {
          console.log('$scope.currentItemIndex', $scope.currentItemIndex, $scope.images.length);

          return ($scope.currentItemIndex + 1) === $scope.images.length;
        }
        function _prevDisabled() {
          return !$scope.currentItemIndex;
        }
        function _updatePagination() {
          $scope.nextDisabled = _nextDisabled();
          $scope.prevDisabled = _prevDisabled();
        }
        function _clearClasses() {
          for (var i=0; i<$scope.images.length; i++) {
            $scope.itemClasses[i] = '';
          }

        }

        // go to slide
        function _goTo(index) {
          console.log('_goTo', index);
          if (index >= $scope.images.length || index < 0 || index === $scope.currentItemIndex) {

            if (!index) {
              $scope.itemClasses[0] = _displayOptions.currentItemClass;
            }
            return;
          }

          _clearClasses();

          $scope.itemClasses[$scope.currentItemIndex] = (index > $scope.currentItemIndex) ? _displayOptions.hidePreviousClass : _displayOptions.hideNextClass;

          var currentClass = (index > $scope.currentItemIndex) ? _displayOptions.showNextClass : _displayOptions.showPreviousClass;
          $scope.itemClasses[index] = _displayOptions.currentItemClass + ' ' + currentClass;

          $scope.currentItemIndex = index;

          _updatePagination();

        }

        // button event handlers
        // consider using the ng-tap directive to remove delay
        $scope.onPrevButtonClicked = function () {
          _goTo($scope.currentItemIndex - 1);
        };
        $scope.onNextButtonClicked = function () {
          _goTo($scope.currentItemIndex + 1);
        };
        
        $scope.$watch('currentItemIndex', function(newVal, oldVal) {
          if (oldVal > newVal) {
            if (typeof $scope.onPrevious === 'function') {
              $scope.onPrevious();
            }
          } else {
            if (typeof $scope.onNext === 'function') {
              $scope.onNext();
            }
          }
        });

      }
    };
});
//Shop Reviews Controller 
mcShopApp.controller('shopReviewsController', function($scope,$sce,$http) {
	if(typeof sessionStorage["shop_user_id"]!='undefined'){
		$scope.data={};
		var user_id = JSON.parse(sessionStorage["shop_user_id"]);
		$('#reviews').addClass('arrow_left');
		var dataObj = {
			user_id			:	user_id
		};	
		$http.put(webServiceUrl+'reviews-and-ratings/'+user_id,dataObj)
		.success(function(response) {
			if(response.value!='0'){
				$scope.getNotifications(user_id);
				var data=response.result;
				var html="";
				var rhtml="";
				$.each(data, function (index,Object) {
						html+='<div class="media">';
						html+='<a class="pull-left" href="#">';
						html+='<img src="https://lh3.googleusercontent.com/uFp_tsTJboUY7kue5XAsGA=w48-c-h48" class="media-object img_profile"></a>';		  
						html+='<div class="media-body">';
						var rating=Object.rating;
						for(var i=1;i<=rating;i++){
							rhtml+='<img class="star" src="images/green-star.png">';
						}for(var j=i;j<=5;j++){
							rhtml+='<img class="star" src="images/gray-star.png">';
						}
						html+='<h4>'+rhtml+'</h4>';
						html+='<h4 class="media-heading">'+Object.user_name+' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Tracking ID: '+Object.tracking_id+'</h4>';
						html+= '<p>'+ Object.review + '</p>';	 	 
						html+='</div>'; 
						html+='</div>';
						rhtml="";
				});
				$scope.revieww		=	$sce.trustAsHtml(html);
			}else{
				$scope.emptyNotifications="No Data Reviews";
			}
		});
	}else{
		location.href="#";
	}
});
mcShopApp.controller('discountsController', function($scope,$sce,$http,ngTableParams,ngDialog) {
	if(typeof sessionStorage["shop_user_id"]!='undefined'){
		$scope.data="";
		var user_id = JSON.parse(sessionStorage["shop_user_id"]);
		$http.get(webServiceUrl+'shop-discount-refunds/'+user_id)
		.success(function(response) {
			var viewDetailes="";
			if(response.value!='0'){
				$scope.getNotifications(user_id);
				var data=response.result;
				$scope.tableParams = new ngTableParams({
					page: 1,            // show first page
					count: 10           // count per page
				}, {
					total: data.length, // length of data
					getData: function($defer, params) {
						$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
					}
				});
				
			}else{
				$scope.emptyNotifications="Discount table is empty";
			}
		});
	}else{
		location.href="#";
	}
});